<template>
  <div class="container">
    <div class="left-column">
      <LeftMenu
        :treeData="treeData"
        :selectedChild="selectedChild"
        @setSelectedChild="handleSelectedChild"
      />
    </div>
    <div class="right-column">
      <RightMenu
        :selectedChildren="getSelectedChildren(treeData, selectedChild)"
        :selectedGrandchild="selectedGrandchild"
        @setSelectedGrandchild="handleSelectedGrandchild"
      />
    </div>
  </div>
</template>

<script>
import LeftMenu from './LeftMenu.vue';
import RightMenu from './RightMenu.vue';

export default {
  components: {
    LeftMenu,
    RightMenu,
  },
  data() {
    return {
      treeData: [
        /* Your tree data here */
      ],
      selectedChild: null,
      selectedGrandchild: null,
    };
  },
  methods: {
    handleSelectedChild(child) {
      this.selectedChild = child;
      this.$nextTick(() => {
        const rightMenu = this.$refs.rightMenu.$el;
        const target = rightMenu.querySelector(`li[data-id="${child.id}"]`);
        if (target) {
          target.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
      });
    },
    handleSelectedGrandchild(grandchild) {
      this.selectedGrandchild = grandchild;
      this.$nextTick(() => {
        const leftMenu = this.$refs.leftMenu.$el;
        const target = leftMenu.querySelector(
          `li[data-id="${this.findParentId(grandchild)}"]`
        );
        if (target) {
          target.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
      });
    },
    getSelectedChildren(tree, selectedChild) {
      return tree.flatMap((item) =>
        item.children &&
        item.children.find((child) => child.id === selectedChild.id)
          ? [item]
          : []
      );
    },
    findParentId(grandchild) {
      let parentId = null;
      this.treeData.forEach((item) => {
        if (item.children) {
          const child = item.children.find(
            (child) =>
              child.children &&
              child.children.find((gc) => gc.id === grandchild.id)
          );
          if (child) {
            parentId = child.id;
          }
        }
      });
      return parentId;
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh; /* Adjust based on your needs */
}
.left-column,
.right-column {
  flex: 1;
  overflow: hidden;
  height: 100%;
  border: 1px solid #ccc; /* Just for visualization */
}
</style>
